package com.gujia.controller;

import com.gujia.model.Question;
import com.gujia.model.User;
import com.gujia.model.ViewObject;
import com.gujia.service.CommentService;
import com.gujia.service.FollowService;
import com.gujia.service.QuestionService;
import com.gujia.service.UserService;
import com.gujia.util.EntityType;
import com.gujia.util.LoginUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by GuJia on 2017/6/17.
 */
@Controller
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    QuestionService questionService;

    @Autowired
    UserService userService;


    @Autowired
    FollowService followService;


    @Autowired
    CommentService commentService;

    @RequestMapping(path={"/","/index"},method = {RequestMethod.GET})
    //@ResponseBody
    public String index(Model model, HttpSession httpSession){
        model.addAttribute("vos",getQuestions(0,0,10));

        return "index";
    }

    @RequestMapping(path={"/user/{userId}"},method = {RequestMethod.GET})
    //@ResponseBody
    public String userIndex(Model model,@PathVariable("userId") int userId){
        model.addAttribute("vos", getQuestions(userId, 0, 10));

        User user = userService.getUser(userId);
        ViewObject vo = new ViewObject();
        vo.set("user", user);
        vo.set("commentCount", commentService.getUserCommentCount(userId));
        vo.set("followerCount", followService.getFollowerCount(EntityType.ENTITY_USER, userId));
        vo.set("followeeCount", followService.getFolloweeCount( EntityType.ENTITY_USER,userId));
        if (LoginUtil.getUser() != null) {
            vo.set("followed", followService.isFollower(LoginUtil.getUser().getId(), EntityType.ENTITY_USER, userId));
        } else {
            vo.set("followed", false);
        }
        model.addAttribute("profileUser", vo);
        return "profile";

    }

    private List<ViewObject> getQuestions(int userId, int offset, int limit) {
        List<Question> questionList = questionService.getLatestQuestions(userId, offset, limit);
        List<ViewObject> vos = new ArrayList<>();
        for (Question question : questionList) {
            ViewObject vo = new ViewObject();
            vo.set("question", question);
            vo.set("user", userService.getUser(question.getUserId()));
            vos.add(vo);
        }
        return vos;
    }




}
